import React, { PureComponent } from 'react'
import { Form, Table, Button, DatePicker, Alert, Input, message } from 'antd'
import { connect } from 'dva'
import moment from 'moment'
import styles from './Index.less'
// import columns from '../propList/columns'

const FormItem = Form.Item
const { RangePicker } = DatePicker

// import { getValue } from '@/utils/utils'
@connect(({ loading, property }) => ({
  property,
  loading: loading.models.property,
}))
@Form.create()
export default class List extends PureComponent {
  state = {
    selectRecords: {},
  }

  componentWillUnmount() {
    this.props.dispatch({
      type: 'property/updateState',
      payload: {
        selectedRowKeys_PropLife: [],
      },
    })
  }

  // 清除选择
  cleanSelectedKeys = () => {
    this.handleSelectRows([])
  }

  // 行选事件
  handleSelectRows = (rowkeys, selectRows) => {
    const { dispatch } = this.props
    dispatch({
      type: 'property/updateState',
      payload: {
        selectedRowKeys_PropLife: rowkeys,
      },
    })
    const { selectRecords } = this.state
    const handleRecords = {}
    rowkeys.forEach(key => {
      if (selectRecords[key]) {
        handleRecords[key] = selectRecords[key]
      } else {
        handleRecords[key] = selectRows.find(row => row.id === key)
      }
    })

    this.setState({
      selectRecords: handleRecords,
    })
  }

  handleRangeChange = (dates, record) => {
    //
    record.startDate = dates[0] ? dates[0].format('YYYY-MM-DD') : ''
    record.endDate = dates[1] ? dates[1].format('YYYY-MM-DD') : ''
  }

  // 表格动作触发事件
  handleListChange = (pg, filtersArg, sorter) => {
    const { dispatch } = this.props
    const { formValues, pagination } = this.props.property
    if (sorter.field && pagination.currentPage === pg.current) {
      return
    }

    const params = {
      ...formValues,
      current: pg.current,
      // size: pg.pageSize,
    }
    dispatch({
      type: 'property/fetchList',
      payload: {
        ...params,
        type: 3,
      },
    })
  }

  handleSubmit = e => {
    //
    e.preventDefault()
    const { dispatch } = this.props
    const { getFieldsValue, setFieldsValue } = this.props.form
    const data = {
      ...getFieldsValue(),
    }

    if (data.day === '') {
      message.info('请输入提前提醒天数')
      return
    }
    if (data.count === '') {
      message.info('请输入连续提醒次数')
      return
    }

    const { selectRecords } = this.state
    if (Object.keys(selectRecords).length === 0) {
      message.info('请选择资产')
      return
    }

    data.day = data.day ? data.day : 7
    data.count = data.count ? data.count : 3

    data.propList = Object.keys(selectRecords).map(key => ({
      id: selectRecords[key].id,
      endDate: selectRecords[key].endDate,
      startDate: selectRecords[key].startDate,
      zcCode: selectRecords[key].zcCode,
    }))

    if (data.propList.find(item => !item.endDate || !item.startDate)) {
      //
      message.info('请确保输入起始时间')
      return
    }

    dispatch({
      type: 'property/setLife',
      payload: data,
      callback: () => {
        setFieldsValue({
          day: '',
          count: '',
        })
      },
    })
  }

  render() {
    const { loading } = this.props
    const { list, pagination, selectedRowKeys_PropLife } = this.props.property
    const { getFieldDecorator } = this.props.form
    const rowSelectionProps = {
      selectedRowKeys: selectedRowKeys_PropLife,
      onChange: (selectedKeys, selectedRows) => {
        this.handleSelectRows(selectedKeys, selectedRows)
      },
    }

    const propColumns = [
      {
        title: '资产编码',
        align: 'center',
        dataIndex: 'zcCode',
        width: 100,
        sorter: (a, b) => {
          if (a.zcType === '0001' && b.zcType === '0002') {
            return -1
          }
          if (a.zcType === '0002' && b.zcType === '0001') {
            return 1
          }
          if (a.zcType === b.zcType) {
            return a.zcCode && a.zcCode.localeCompare(b.zcCode)
          }
        },
        sortDirections: ['descend', 'ascend'],
      },
      {
        title: '资产名称',
        align: 'center',
        sorter: (a, b) => {
          if (a.zcType === '0001' && b.zcType === '0002') {
            return -1
          }
          if (a.zcType === '0002' && b.zcType === '0001') {
            return 1
          }
          if (a.zcType === b.zcType) {
            return a.zcName && a.zcName.localeCompare(b.zcName)
          }
        },
        dataIndex: 'zcName',
        width: 80,
      },
      {
        title: '资产分类',
        align: 'center',
        width: 80,
        dataIndex: 'zcClassName',
      },
      {
        title: '资产类型',
        align: 'center',
        width: 80,
        dataIndex: 'zcTypeName',
      },
      {
        title: '所在位置',
        align: 'center',
        width: 100,
        dataIndex: 'zcSeatName',
      },
      {
        title: '使用人',
        align: 'center',
        width: 80,
        dataIndex: 'useOperatorName',
      },
      {
        title: '入库时间',
        align: 'center',
        width: 80,
        dataIndex: 'gmtRk',
      },
      {
        title: '状态',
        align: 'center',
        width: 60,
        dataIndex: 'statusName',
      },
      {
        title: '操作',
        align: 'center',
        width: 250,
        // fixed: 'right',
        render: (text, record) => {
          const { startDate } = record
          const { endDate } = record
          const defaultValue = []
          if (startDate) {
            defaultValue.push(moment(startDate, 'YYYY-MM-DD'))
          }
          if (endDate) {
            defaultValue.push(moment(endDate, 'YYYY-MM-DD'))
          }
          return (
            <div>
              <RangePicker
                defaultValue={defaultValue}
                onChange={dates => {
                  this.handleRangeChange(dates, record)
                }}
              ></RangePicker>
            </div>
          )
        },
      },
    ]

    return (
      <div className={styles.standardTable}>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            paddingTop: 15,
            paddingBottom: 15,
            backgroundColor: '#fff',
          }}
        >
          <Form onSubmit={this.handleSubmit} className={styles.lifeForm} layout="inline">
            <Button icon="plus" type="primary" htmlType="submit" loading={loading}>
              提交保存
            </Button>
            <div className={styles.lifeForm_item}>
              提前
              <FormItem style={{ display: 'inline-block' }}>
                {getFieldDecorator('day', {
                  initialValue: '',
                  getValueFromEvent: e => {
                    const { target } = e
                    target.value = target.value.replace(/^(0+)|[^\d]+/g, '')
                    return target.value
                  },
                  // rules: [{ required: true, message: '不能为空' }],
                })(<Input type="text" maxLength="2" />)}
              </FormItem>
              天提醒
            </div>
            <div className={styles.lifeForm_item}>
              连续提醒
              <FormItem style={{ display: 'inline-block' }}>
                {getFieldDecorator('count', {
                  initialValue: '',
                  getValueFromEvent: e => {
                    const { target } = e
                    target.value = target.value.replace(/^(0+)|[^\d]+/g, '')
                    return target.value
                  },
                })(<Input type="text" maxLength="2" />)}
              </FormItem>
              次
            </div>
          </Form>
        </div>
        <Alert
          style={{ marginBottom: 8 }}
          message={
            <div>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys_PropLife.length}</a>{' '}
              项&nbsp;&nbsp;
              <a style={{ marginLeft: 24 }} onClick={() => this.handleSelectRows([])}>
                清空选择
              </a>
            </div>
          }
          type="info"
          showIcon
        />
        <Table
          loading={loading}
          size="small"
          bordered
          dataSource={list}
          rowKey={record => record.id}
          pagination={pagination}
          columns={propColumns}
          onChange={this.handleListChange}
          rowSelection={rowSelectionProps}
          // scroll={{ x: 800 }}
        />
      </div>
    )
  }
}
